package edu.ustb.mis.dm.impl.data;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.List;
import edu.ustb.mis.dm.Constants;
import edu.ustb.mis.dm.interfaces.data.DataOutput;
import edu.ustb.mis.dm.model.ClusterResult;

public class TextDataOutput implements DataOutput<ClusterResult> {
	private final String fileName;

	public TextDataOutput(final String index, final double threshhold) {
		this.fileName = new StringBuffer(index).append("-").append(Constants.THRESHHOLD_FORMAT.format(threshhold)).append(Constants.TXT_SUFFIX).toString();
	}

	public TextDataOutput(final String index, final int times) {
		this.fileName = new StringBuffer(index).append("-").append(times).append(Constants.TXT_SUFFIX).toString();
	}

	private void appendOutPutString(final StringBuffer sbf, final int i, final ClusterResult cr) {
		sbf.append("第").append(i + 1).append("类").append(Constants.LINE_SPLIT).append(cr.getClassIDList()).append(Constants.LINE_SPLIT).append("差异度：").append(
				cr.getDissimilarity()).append(Constants.LINE_SPLIT);
	}

	public void writefile(final List<ClusterResult> crList) {
		try {
			final BufferedWriter bw = new BufferedWriter(new FileWriter(fileName));
			final StringBuffer sbf = new StringBuffer();
			final int size = crList.size();
			ClusterResult cr;
			for (int i = 0; i < size; i++) {
				cr = crList.get(i);
				appendOutPutString(sbf, i, cr);
			}
			bw.write(sbf.toString());
			bw.flush();
			bw.close();
		} catch (final IOException e) {
			e.printStackTrace();
		}
	}
}
